package org.kl.bf.web.basic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.OnlineSession;
import org.apache.shiro.session.mgt.SessionGrid;
import org.apache.shiro.session.mgt.OnlineSession.OnlineStatus;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * @Author hqm
 * @CreateTime 2014年6月19日 上午10:08:57
 */
@Controller
@RequestMapping(value = "/basic/sessions")
public class SessionController extends BasicController {
	@Autowired
	private SessionDAO sessionDAO;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/sessions";
	}

	@RequestMapping()
	public String list(Model model) {
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		model.addAttribute("sessions", sessions);
		model.addAttribute("sesessionCount", sessions.size());
		return "sessions/list";
	}

	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(Model model, ServletRequest request) {
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		List<SessionGrid> sgList = new ArrayList<SessionGrid>();
		for (Session session : sessions) {
			if (session instanceof OnlineSession) {
				OnlineSession os = (OnlineSession) session;
				SessionGrid sg = SessionGrid.fromOnlineSession(os);
				if (sg != null) {
					sgList.add(sg);
				}
			}
		}
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(sgList);
		grid.setTotal(sgList.size());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequestMapping("/{sessionId}/forceLogout")
	@ResponseBody
	public String forceLogout(@PathVariable("sessionId") String sessionId, RedirectAttributes redirectAttributes) {
		try {
			Session session = sessionDAO.readSession(sessionId);
			if (session != null) {
				if (session instanceof OnlineSession) {
					OnlineSession os = (OnlineSession) session;
					os.setStatus(OnlineStatus.force_logout);
					os.setAttribute(BasicConstants.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
				}
			}
		} catch (Exception e) {
			return ajaxMsg("", false, null);
		}
		return ajaxMsg("强制退出成功！", true, null);
	}
}
